package com.example.demo.common;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author: htc
 * @date: Created in 15:29 2019/1/2.
 */
public class SystemUtils {
    /**
     * 获取mac地址
     *
     * @return
     */
    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            byte[] mac = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || networkInterface.isPointToPoint()) {
                    continue;
                } else {
                    mac = networkInterface.getHardwareAddress();
                    if (null != mac) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                        if (sb.length() > 0) {
                            return sb.toString();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取ip地址
     *
     * @return
     */
    public static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetworkInterface = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetworkInterface.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) allNetworkInterface.nextElement();
                if (networkInterface.isPointToPoint() || networkInterface.isUp() || networkInterface.isLoopback()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        System.out.println(getMacAddress());
        System.out.println(getIpAddress());
    }
}
